﻿namespace 订单API
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public Product(string id, string name, double price)
        {
            Id = id;
            Name = name;
            Price = price;
        }
        public override string ToString()
        {
            return $"商品ID: {Id}, 名称: {Name}, 价格: {Price:C}";
        }
        public override bool Equals(object? obj)
        {
            return obj is Product product &&
                Id == product.Id &&
                Name == product.Name &&
                Price == product.Price;

        }
        public override int GetHashCode()
        {
            return HashCode.Combine(Id, Name, Price);
        }
    }
    public class Customer
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public Customer(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public override bool Equals(object? obj)
        {
            return obj is Customer customer &&
                Id == customer.Id &&
                Name == customer.Name;
        }
        public override string ToString()
        {
            return $"客户ID为{Id},客户姓名为{Name} ";
        }
        public override int GetHashCode()
        {
            return HashCode.Combine(Id, Name);
        }
    }
    public class Order
    {
        public Customer Customer { get; set; }
        public string OrderId { get; set; }
        public List<Orderdetail> DetailList = new List<Orderdetail>();
        public double TotalAmount => DetailList.Sum(d => d.Amount);

        public Order(Customer customer, string orderid)
        {
            Customer = customer;
            OrderId = orderid;
        }
        public override bool Equals(object? obj)
        {
            return obj is Order order &&
                OrderId == order.OrderId &&
                Customer == order.Customer;
        }
        public void AddDetail(Orderdetail detail)
        {
            if (DetailList.Contains(detail))
            {
                throw new ArgumentException("订单明细已存在");
            }
            DetailList.Add(detail);
        }
        public void RemoveDetail(Product product)
        {
            var detail = DetailList.FirstOrDefault(d => d.Product.Equals(product));
            if (detail == null)
            {
                throw new ArgumentException("订单中不包含该商品");
            }
            DetailList.Remove(detail);
        }
        public override int GetHashCode()
        {
            return HashCode.Combine(OrderId);
        }
        public override string ToString()
        {
            double TotalAmount = DetailList.Sum(d => d.Amount);
            return $" 订单号:{OrderId} {Customer} 订单明细：\n{DetailList}\n 总金额：{TotalAmount}";
        }
    }
    public class Orderdetail
    {
        public Product Product { get; set; }
        public int Quantity { get; set; }
        public double Amount => Product.Price * Quantity;
        public Orderdetail(Product product, int quantity)
        {
            Product = product;
            Quantity = quantity;
        }
        public override string ToString()
        {
            return $"{Product},数量:{Quantity},小结:{Amount}";
        }
        public override bool Equals(object? obj)
        {
            return obj is Orderdetail orderdetail &&
                    orderdetail.Product == Product &&
                    orderdetail.Quantity == Quantity;
        }
        public override int GetHashCode()
        {
            return HashCode.Combine(Product, Quantity);
        }
    }
    public class OrderService
    {
        private List<Order> Orders = new List<Order>();
        public void Add(Order order)
        {
            if (Orders.Contains(order))
            {
                throw new ArgumentException("添加失败， 该订单已存在");
            }
            Orders.Add(order);
        }
        public void Remove(string orderid)
        {
            var order = Orders.FirstOrDefault(o => o.OrderId == orderid);
            if (order == null)
            {
                throw new ArgumentException("删除失败，不存在该订单");
            }
            Orders.Remove(order);
        }
        public void AddOrderDetail(string orderId, Orderdetail detail)
        {
            var order = Orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
            {
                throw new ArgumentException($"订单 {orderId} 不存在");
            }
            order.AddDetail(detail);
        }

        public void RemoveOrderDetail(string orderId, Product product)
        {
            var order = Orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
            {
                throw new ArgumentException($"订单 {orderId} 不存在");
            }
            order.RemoveDetail(product);
        }
        public List<Order> GetAllOrders()
        {
            return Orders.ToList();
        }
        public List<Order> QueryByOrderId(string orderId)
        {
            return Orders.Where(o => o.OrderId.Contains(orderId))
                         .ToList();
        }

        public List<Order> QueryByProductName(string productName)
        {
            return Orders.Where(o => o.DetailList.Any(d => d.Product.Name.Contains(productName)))
                         .ToList();
        }

        // 按客户查询
        public List<Order> QueryByCustomer(string customerName)
        {
            return Orders.Where(o => o.Customer.Name.Contains(customerName))
                         .ToList();
        }
        public void SortOrders()
        {
            Orders = Orders.OrderBy(o => o.OrderId).ToList();
        }

        public void SortOrders(Func<Order, object> lamda)
        {
            Orders = Orders.OrderBy(lamda).ToList();
        }

    }
    class Program
    {
        static OrderService orderService = new OrderService();
        static List<Product> products = new List<Product>();
        static List<Customer> customers = new List<Customer>();

        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("\n=== 订单管理系统 ===");
                Console.WriteLine("1. 添加订单");
                Console.WriteLine("2. 删除订单");
                Console.WriteLine("3. 修改订单");
                Console.WriteLine("4. 查询订单");
                Console.WriteLine("5. 排序订单");
                Console.WriteLine("6. 显示所有订单");
                Console.WriteLine("0. 退出");
                Console.Write("请选择操作: ");

                if (!int.TryParse(Console.ReadLine(), out int choice))
                {
                    Console.WriteLine("无效输入，请重新选择");
                    continue;
                }

                try
                {
                    switch (choice)
                    {
                        case 1:
                            AddOrder();
                            break;
                        case 2:
                            RemoveOrder();
                            break;
                        case 3:
                            ModifyOrder();
                            break;
                        case 4:
                            QueryOrders();
                            break;
                        case 5:
                            SortOrders();
                            break;
                        case 6:
                            DisplayAllOrders();
                            break;
                        case 0:
                            return;
                        default:
                            Console.WriteLine("无效选择，请重新输入");
                            break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"操作失败: {ex.Message}");
                }
            }
        }
        static void AddOrder()
        {
            Console.Write("输入订单号: ");
            string orderId = Console.ReadLine();

            Console.WriteLine("可选客户:");
            customers.ForEach(c => Console.WriteLine($"  {c.Id}: {c.Name}"));
            Console.Write("选择客户ID: ");
            string customerId = Console.ReadLine();
            var customer = customers.FirstOrDefault(c => c.Id == customerId);
            if (customer == null)
            {
                throw new ArgumentException("无效的客户ID");
            }

            var order = new Order(customer, orderId);

            while (true)
            {
                Console.WriteLine("\n当前商品列表:");
                products.ForEach(p => Console.WriteLine($"  {p.Id}: {p.Name} - {p.Price:C}"));
                Console.Write("输入要添加的商品ID(输入空行结束): ");
                string productId = Console.ReadLine();
                if (string.IsNullOrEmpty(productId)) break;

                var product = products.FirstOrDefault(p => p.Id == productId);
                if (product == null)
                {
                    Console.WriteLine("无效的商品ID");
                    continue;
                }

                Console.Write("输入数量: ");
                if (!int.TryParse(Console.ReadLine(), out int quantity) || quantity <= 0)
                {
                    Console.WriteLine("无效的数量");
                    continue;
                }

                try
                {
                    order.AddDetail(new Orderdetail(product, quantity));
                    Console.WriteLine("商品添加成功");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"添加失败: {ex.Message}");
                }
            }

            orderService.Add(order);
            Console.WriteLine("订单添加成功");
        }

        static void RemoveOrder()
        {
            Console.Write("输入要删除的订单号: ");
            string orderId = Console.ReadLine();
            orderService.Remove(orderId);
            Console.WriteLine("订单删除成功");
        }

        static void ModifyOrder()
        {
            Console.Write("输入要修改的订单号: ");
            string orderId = Console.ReadLine();

            Console.WriteLine("1. 添加商品");
            Console.WriteLine("2. 删除商品");
            Console.Write("选择操作: ");
            if (!int.TryParse(Console.ReadLine(), out int choice) || (choice != 1 && choice != 2))
            {
                Console.WriteLine("无效选择");
                return;
            }

            if (choice == 1)
            {
                Console.WriteLine("可选商品:");
                products.ForEach(p => Console.WriteLine($"  {p.Id}: {p.Name} - {p.Price:C}"));
                Console.Write("输入要添加的商品ID: ");
                string productId = Console.ReadLine();
                var product = products.FirstOrDefault(p => p.Id == productId);
                if (product == null)
                {
                    throw new ArgumentException("无效的商品ID");
                }

                Console.Write("输入数量: ");
                if (!int.TryParse(Console.ReadLine(), out int quantity) || quantity <= 0)
                {
                    throw new ArgumentException("无效的数量");
                }

                orderService.AddOrderDetail(orderId, new Orderdetail(product, quantity));
                Console.WriteLine("商品添加成功");
            }
            else
            {
                Console.Write("输入要删除的商品ID: ");
                string productId = Console.ReadLine();
                var product = products.FirstOrDefault(p => p.Id == productId);
                if (product == null)
                {
                    throw new ArgumentException("无效的商品ID");
                }

                orderService.RemoveOrderDetail(orderId, product);
                Console.WriteLine("商品删除成功");
            }
        }

        static void QueryOrders()
        {
            Console.WriteLine("1. 按订单号查询");
            Console.WriteLine("2. 按商品名称查询");
            Console.WriteLine("3. 按客户查询");
            Console.Write("选择查询方式: ");
            if (!int.TryParse(Console.ReadLine(), out int choice) || choice < 1 || choice > 3)
            {
                Console.WriteLine("无效选择");
                return;
            }

            List<Order> result = null;
            switch (choice)
            {
                case 1:
                    Console.Write("输入订单号: ");
                    result = orderService.QueryByOrderId(Console.ReadLine());
                    break;
                case 2:
                    Console.Write("输入商品名称: ");
                    result = orderService.QueryByProductName(Console.ReadLine());
                    break;
                case 3:
                    Console.Write("输入客户名称: ");
                    result = orderService.QueryByCustomer(Console.ReadLine());
                    break;
            }

            if (result == null || result.Count == 0)
            {
                Console.WriteLine("没有找到匹配的订单");
                return;
            }

            Console.WriteLine($"找到 {result.Count} 个订单:");
            foreach (var order in result)
            {
                Console.WriteLine(order);
                Console.WriteLine("------------------");
            }
        }

        static void SortOrders()
        {
            Console.WriteLine("1. 按订单号排序");
            Console.WriteLine("2. 按总金额排序");
            Console.Write("选择排序方式: ");
            if (!int.TryParse(Console.ReadLine(), out int choice) || choice < 1 || choice > 2)
            {
                Console.WriteLine("无效选择");
                return;
            }

            switch (choice)
            {
                case 1:
                    orderService.SortOrders(o => o.OrderId);
                    break;
                case 2:
                    orderService.SortOrders(o => o.TotalAmount);
                    break;
            }

            Console.WriteLine("排序完成");
            DisplayAllOrders();
        }


        static void DisplayAllOrders()
        {
            var orders = orderService.GetAllOrders();
            if (orders.Count == 0)
            {
                Console.WriteLine("没有订单");
                return;
            }

            Console.WriteLine($"共有 {orders.Count} 个订单:");
            foreach (var order in orders)
            {
                Console.WriteLine(order);
                Console.WriteLine("==================");
            }
        }
    }

}
